const { makeExecutableSchema } = require('graphql-tools')

const fs = require('fs')
const path = require('path')

const root = path.join(__dirname)
import _ from 'lodash'
import GraphQLJSON from 'graphql-type-json'

let resolvers = []
let schemas = []
let dataloaders = {}

schemas.push(`
  type Query {
    appName: String!
  }
`)

schemas.push(`
  type Mutation {
    setAppName: String
  }
`)

fs.readdirSync(root).forEach(filename => {
  if (filename == 'index.js') return
  let resolver = null
  try {
    resolver = require(path.join(root, filename, 'resolver.js'))
    resolvers.push(resolver)
  } catch (e) {
    console.info(e)
  }

  let schema = ''
  try {
    schema = require(path.join(root, filename, 'schema.js'))
    schemas.push(schema)
  } catch (e) {
    console.info(e)
  }

  let dataloader = null
  try {
    let file = path.join(root, filename, 'dataloaders.js')
    if (fs.existsSync(file)) {
      Object.assign(dataloaders, require(file))
    }
  } catch (e) {
    console.info(e)
  }
})

module.exports = {
  schema: makeExecutableSchema({
    typeDefs: schemas,
    resolvers: resolvers
  }),
  dataloaders
}
